<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let arr = [1, 2, 3, 4];
            let sum = arr.reduce((tol, cur) => {
                return (tol += cur);
            }, 0);
            let obj = {
                name: 'zs',
            };
            console.log(sum); // 10
            // obj.reduce();
            Array.prototype.myReduce = function (callback, InitialValue) {
                if (typeof callback !== 'function') {
                    throw new Error('传入第一个参数必须是函数');
                }
                const array = this;
                // 如果没有传InitaialValue初始值时，初始值默认为数组的第一项即array[0]
                let result = InitialValue || array[0];
                for (let i = 0; i < array.length; i++) {
                    // 如果没有传第二个参数InitialValue初始值，当前数组第一项就不在进入循环
                    if (!InitialValue && i == 0) {
                        continue;
                    }
                    result = callback(result, array[i], i, this);
                }
                return result;
            };
            let result = arr.myReduce((tol, cur, index, arr) => {
                return (tol += cur);
            }, 0);
            console.log(result); // 10
        </script>
    </body>
</html>
